home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
SGI Developer Toolbox 6.1
/
SGI Developer Toolbox 6.1 - Disc 4.iso
/
public
/
bit
/
src
/
ulib
/
readfloat.c
< prev
next >
Wrap
C/C++ Source or Header
|
1994-08-01
|
3KB
|
139 lines
/***********************************************************************
* $Id: readfloat.c,v 0.80 1994/02/24 09:48:11 zhao Exp $
*
*. Copyright(c) 1993,1994 by T.C. Zhao
* All rights reserved.
*.
* Read a float from a file. Valid sepertors are SPACE, \t \n
* # introduces a comment that ends at \n
*
* The floating number must be of the form [+-]nnn.xxx, i.e.,
* no e and E is permitted
*
* bad_character is defined in readint.c
***********************************************************************/
#if !defined(lint) && defined(F_ID)
char *id_rfloat = "$Id: readfloat.c,v 0.80 1994/02/24 09:48:11 zhao Exp $";
#endif
#include <stdio.h>
#include <ctype.h> /* for isdigit */
#include "ulib.h"
#define IS_FS(c) ( (c) == ' ' || (c) == '\t' || (c) == '\n')
#define IS_COMMENT(c) ( (c) == '#')
extern int skip_comment(FILE * fp);
extern void bad_character(int);
double
readfloat(FILE * fp)
{
register int c;
register double num1 = 0.0, num2 = 0.0; /* must be in double */
register double sign = 1.0;
do
{
c = getc(fp);
while (IS_COMMENT(c))
c = skip_comment(fp);
}
while (IS_FS(c));
if (c == '-')
{
sign = -1.0;
c = getc(fp);
}
else if (c == '+')
{
sign = 1.0;
c = getc(fp);
}
if (!isdigit(c))
{
bad_character(c);
return -10000000.0;
}
do
{
num1 = 10.0 * num1 + c - '0';
c = getc(fp);
}
while (isdigit(c));
/*
* the only permissible char at this point is . or FS. if we get an FS,
* we are done, else, read the fractional part
*/
if (IS_FS(c))
return (num1 * sign);
else if (c == '.')
{ /* ok, do the fractional part */
register double fact = 0.1;
while ((c = getc(fp)) != EOF && isdigit(c))
{
num2 = num2 + fact * (c - '0');
fact *= 0.1;
}
return ((num1 + num2) * sign);
}
else
{ /* error */
bad_character(c);
return -10000000.0;
}
}
/* Read a positive floating number. return EOF if error */
double
readpfloat(FILE * fp)
{
register int c;
register double num1 = 0, num2 = 0;
do
{
c = getc(fp);
while (IS_COMMENT(c))
c = skip_comment(fp);
}
while (IS_FS(c));
if (!(c == '+' || isdigit(c)))
{
bad_character(c);
return EOF;
}
if (!isdigit(c))
c = getc(fp);
do
{
num1 = 10.0 * num1 + c - '0';
c = getc(fp);
}
while (isdigit(c));
if (IS_FS(c)) /* we are done */
return num1;
else if (c == '.')
{ /* read the fractional part */
register double fact = 0.1;
while ((c = getc(fp)) != EOF && isdigit(c))
{
num2 = num2 + fact * (c - '0');
fact *= 0.1;
}
return (num1 + num2);
}
else
{ /* error */
bad_character(c);
return EOF;
}
}